<?php

/**
 * 集合类
 * User: 4399-0661
 * Date: 15-4-11
 * Time: 下午2:14
 */
class LibConnection implements \Iterator, \ArrayAccess, \Countable
{
    public $info = array();

    static public function instance($array = [])
    {
        $class = get_called_class();
        /**
         * @var \LibConnection $self
         */
        $self = new $class();
        $self->setInfo($array);
        return $self;
    }

    public function setInfo($array)
    {
        if (!is_array($array)) {
            $array = [$array];
        }
        $this->info = $array;
    }

    /**
     * 数组当前的值
     * @return mixed
     */
    public function current()
    {
        return current($this->info);
    }

    /**
     * 数组当前的key
     * @return mixed
     */
    public function key()
    {
        return key($this->info);
    }

    /**
     * 数组的指针指向下一个元素
     * @return mixed|void
     */
    public function next()
    {
        return next($this->info);
    }

    /**
     * 重置数组指针
     * @return mixed|void
     */
    public function rewind()
    {
        return reset($this->info);
    }

    /**
     * 验证当前元素是否存在
     * @return bool
     */
    public function valid()
    {
        return $this->current() !== false;
    }

    /**
     * 判断一个元素是否定义
     * @param mixed $offset
     * @return bool|void
     */
    public function offsetExists($offset)
    {
        return isset($this->info[$offset]);
    }

    /**
     * 返回一个元素的值
     * @param mixed $offset
     * @return mixed|void
     */
    public function offsetGet($offset)
    {
        return $this->info[$offset];
    }

    /**
     * 设置一个元素的值
     * @param mixed $offset
     * @param mixed $value
     */
    public function offsetSet($offset, $value)
    {
        $this->info[$offset] = $value;
    }

    /**
     * 删除一个元素的值
     * @param mixed $offset
     */
    public function offsetUnset($offset)
    {
        unset($this->info[$offset]);
    }

    /**
     * 让对象可以被用于count函数的能力
     * @return int
     */
    public function count()
    {
        return count($this->info);
    }

    public function each($func)
    {
        $args = func_get_args();
        array_shift($args);
        if (!is_array($this->info)) return false;

        foreach ($this->info as $k => &$item) {
            $t = array(&$item, $k);
            $t = array_merge($t, $args);
            if (call_user_func_array($func, $t) !== false) {

            } else {
                return false;
            }
        }
    }

    public function appendElement($datas = [])
    {
        $this->setInfo($datas);
    }

    /**
     * 得到二维数组里面某个字段的值得集合(去重)
     * @param $field
     * @return array
     */
    public function getArrayFieldValue($field)
    {
        if (!$field) {
            return [];
        }
        $result = [];
        foreach ($this->info as $info) {
            if (isset($info[$field])) {
                $result[] = $info[$field];
            }
        }
        return array_unique($result);
    }


} 